<template>
  <common-header/>
  
  <!-- 简化后的搜索区域 -->
  <div class="search-container">
    <n-card :bordered="false" class="search-card">
      <n-space vertical :size="8">
        <n-input-group>
          <n-input
            v-model:value="searchKeyword"
            placeholder="搜索附近的健身场所..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <n-icon :component="Search" />
            </template>
          </n-input>
          <n-button type="primary" @click="handleSearch" :loading="isSearching">
            搜索
          </n-button>          <n-button @click="handleReset" :disabled="isSearching">
            <template #icon>
              <n-icon><LocationOutline /></n-icon>
            </template>
            重置位置
          </n-button>          <n-button @click="handleGoToGymDetail" type="info">
            <template #icon>
              <n-icon><Business /></n-icon>
            </template>
            查看场馆详情
          </n-button>
        </n-input-group>

        <!-- 搜索建议标签 -->
        <n-space class="search-suggestions">
          <n-tag
            v-for="suggestion in searchSuggestions"
            :key="suggestion"
            :bordered="false"
            round
            size="small"
            clickable
            @click="handleSuggestionClick(suggestion)"
          >
            {{ suggestion }}
          </n-tag>
        </n-space>
      </n-space>
    </n-card>
  </div>

  <!-- 地图容器 -->
  <div id="container" class="map-container"></div>
  
  <!-- POI搜索结果面板 -->
  <div id="my-panel" class="search-panel"></div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import CommonHeader from '../../components/CommonHeader.vue'
import AMapLoader from '@amap/amap-jsapi-loader';
import { Search, LocationOutline, Business } from '@vicons/ionicons5'
import { useMessage } from 'naive-ui'
import axios from 'axios'

// 基础变量初始化
const router = useRouter();
const map = ref(null);
const placeSearch = ref(null);
const message = useMessage();
const currentPosition = ref(null);
const geolocation = ref(null);
const searchKeyword = ref('');
const isSearching = ref(false);
const BASE_URL = window.BASE_URL;

// 搜索建议列表
const searchSuggestions = [
  // 健身相关场馆
  '健身房',
  '瑜伽馆',
  '游泳馆',
  
  // 球类运动场馆
  '篮球馆',
  '羽毛球馆',
  '乒乓球馆',
  '网球场',
  '台球厅'
];

// 高德地图安全密钥配置
window._AMapSecurityConfig = {
  securityJsCode: "b8c254e6d81c71ad75a649092084e6ea"
};

onMounted(async () => {
  try {
    const AMap = await AMapLoader.load({
      key: "795365efadb7998bea6425390ba6692a",
      version: "2.0",
      plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.PlaceSearch", "AMap.Geolocation"]
    });

    // 初始化地图
    map.value = new AMap.Map("container", {
      viewMode: "2D",
      zoom: 15
    });

    // 初始化地图控件
    map.value.addControl(new AMap.Scale());
    map.value.addControl(new AMap.ToolBar());

    // 初始化POI搜索
    placeSearch.value = new AMap.PlaceSearch({
      pageSize: 10,
      extensions: 'all',
      map: map.value,
      panel: "my-panel",
      autoFitView: true
    });

    // 配置定位
    geolocation.value = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      zoomToAccuracy: true,
      buttonPosition: 'RB'
    });

    map.value.addControl(geolocation.value);

    // 获取当前位置
    await new Promise((resolve, reject) => {
      geolocation.value.getCurrentPosition((status, result) => {
        if (status === 'complete') {
          currentPosition.value = result.position;
          map.value.setCenter(result.position);
          resolve();
        } else {
          message.error('定位失败，请检查位置权限');
          reject();
        }
      });
    });

  } catch (error) {
    console.error("地图初始化失败:", error);
    message.error("地图加载失败");
  }
});

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    message.warning('请输入搜索关键词');
    return;
  }

  if (!currentPosition.value) {
    message.warning('正在获取位置信息，请稍候...');
    return;
  }

  isSearching.value = true;
  try {
    placeSearch.value.searchNearBy(
      searchKeyword.value,
      currentPosition.value,
      5000,
      async (status, result) => {
        if (status === 'complete') {
          console.log('POI 搜索结果:', result.poiList.pois);
          // 过滤健身场馆数据
          const gymData = result.poiList.pois.filter(poi => 
            poi.type.includes('健身') || 
            poi.type.includes('运动') || 
            poi.type.includes('体育') ||
            poi.type.includes('瑜伽') ||
            poi.type.includes('游泳')
          );
          
          // 存储到localStorage（保留原有功能）
          localStorage.setItem('nearbyGyms', JSON.stringify(gymData));
          
          // 新增：自动存储POI数据到后端数据库
          if (gymData.length > 0) {
            await savePOIGymsToDatabase(gymData);
            message.success(`找到 ${gymData.length} 个健身场馆，已自动保存到数据库`);
          } else {
            message.info('未找到相关健身场馆');
          }
        } else {
          console.error('POI 搜索失败:', result);
          message.error('搜索失败，请稍后重试');
        }
      }
    );
  } catch (error) {
    console.error('搜索失败:', error);
    message.error('搜索失败');
  } finally {
    isSearching.value = false;
  }
};

// 新增：根据搜索关键词确定场馆类型
const getGymTypeFromKeyword = (keyword) => {
  const normalizedKeyword = keyword.trim().toLowerCase();
  
  // 根据搜索关键词映射到具体的场馆类型
  // 球类运动场馆
  if (normalizedKeyword.includes('羽毛球')) return '羽毛球馆';
  if (normalizedKeyword.includes('乒乓球')) return '乒乓球馆';
  if (normalizedKeyword.includes('篮球')) return '篮球馆';
  if (normalizedKeyword.includes('网球')) return '网球场';
  if (normalizedKeyword.includes('台球') || normalizedKeyword.includes('桌球')) return '台球厅';
  if (normalizedKeyword.includes('保龄球')) return '保龄球馆';
  if (normalizedKeyword.includes('高尔夫')) return '高尔夫球场';
  if (normalizedKeyword.includes('足球')) return '足球场';
  if (normalizedKeyword.includes('排球')) return '排球馆';
  
  // 健身相关场馆
  if (normalizedKeyword.includes('瑜伽')) return '瑜伽馆';
  if (normalizedKeyword.includes('游泳')) return '游泳馆';
  if (normalizedKeyword.includes('24小时') || normalizedKeyword.includes('24h')) return '24小时健身房';
  if (normalizedKeyword.includes('私教')) return '私教工作室';
  if (normalizedKeyword.includes('健身房') || normalizedKeyword.includes('健身')) return '健身房';
  
  // 其他运动场馆
  if (normalizedKeyword.includes('武术') || normalizedKeyword.includes('跆拳道') || normalizedKeyword.includes('空手道')) return '武术馆';
  if (normalizedKeyword.includes('舞蹈')) return '舞蹈工作室';
  if (normalizedKeyword.includes('攀岩')) return '攀岩馆';
  if (normalizedKeyword.includes('滑冰') || normalizedKeyword.includes('溜冰')) return '滑冰场';
  if (normalizedKeyword.includes('体操')) return '体操馆';
  if (normalizedKeyword.includes('击剑')) return '击剑馆';
  
  // 综合场馆
  if (normalizedKeyword.includes('运动中心')) return '运动中心';
  if (normalizedKeyword.includes('体育馆')) return '体育馆';
  if (normalizedKeyword.includes('体育场')) return '体育场';
  
  // 如果没有匹配的关键词，返回通用类型
  return '健身场所';
};

// 新增：将POI数据存储到后端数据库
const savePOIGymsToDatabase = async (gymData) => {
  try {
    // 根据当前搜索关键词确定场馆类型
    const gymType = getGymTypeFromKeyword(searchKeyword.value);
      // 转换POI数据格式以匹配后端POIGymParam结构
    const poiGyms = gymData.map(poi => ({
      id: poi.id,
      name: poi.name,
      type: gymType, // 使用根据搜索关键词确定的类型
      address: poi.address,
      area: poi.adname || poi.cityname, // 使用区域名称或城市名称
      phone: poi.tel || null,
      longitude: poi.location ? poi.location.lng : null,
      latitude: poi.location ? poi.location.lat : null,
      openingHours: poi.business?.opentime || null, // 营业时间
      description: `${gymType} | ${poi.type}` + (poi.business?.rating ? ` | 评分: ${poi.business.rating}` : '') , // 包含用户搜索类型和POI原始类型
      photos: poi.photos || [], // 包含POI的photos数组
      rating: poi.rating || null, // 包含评分
      tel: poi.tel || null, // 包含电话
      adname: poi.adname || null, // 包含区域名称
      distance: poi.distance || null // 包含距离
    }));

    console.log('准备发送到后端的POI数据:', poiGyms);

    // 调用后端API存储POI数据
    const response = await axios.post(`${BASE_URL}/v1/gym/savePOIGyms`, poiGyms, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.data.code === 2000) {
      console.log(`成功存储 ${response.data.data} 个POI场馆到数据库`);
    } else {
      console.error('存储POI数据失败:', response.data.msg);
      message.warning('场馆数据存储失败，但搜索结果已保存到本地');
    }
  } catch (error) {
    console.error('存储POI数据到数据库失败:', error);
    // 不显示错误消息给用户，因为搜索功能本身是成功的
    console.warn('POI数据自动存储功能暂时不可用，搜索结果已保存到本地');
  }
};

// 处理重置位置
const handleReset = () => {
  if (currentPosition.value) {
    map.value.setZoomAndCenter(16, currentPosition.value);
    searchKeyword.value = '';
    const panel = document.getElementById('my-panel');
    if (panel) panel.innerHTML = '';
    message.success('已重置到当前位置');
  } else {
    message.warning('正在获取位置信息...');
  }
};

// 处理搜索建议点击
const handleSuggestionClick = (suggestion) => {
  searchKeyword.value = suggestion;
  handleSearch();
};

// 跳转到场馆详情页
const handleGoToGymDetail = () => {
  router.push('/gym');
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: calc(100vh - 60px);
  position: relative;
}

.search-container {
  position: absolute;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  width: 600px;
}

.search-card {
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
}

.search-panel {
  position: absolute;
  top: 140px;
  right: 20px;
  width: 350px;
  max-height: calc(100vh - 180px);
  overflow-y: auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 99;
}

/* 自定义搜索结果面板样式 */
:deep(.amap-lib-placeSearch) {
  border: none !important;
  background-color: white !important;
  padding: 12px !important;
}

:deep(.amap-lib-placeSearch .poibox) {
  border-bottom: 1px solid #eee;
  padding: 12px 0;
}

:deep(.amap-lib-placeSearch .poibox:last-child) {
  border-bottom: none;
}

:deep(.amap-lib-placeSearch .poibox .poi-title) {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

:deep(.amap-lib-placeSearch .poibox .poi-info) {
  font-size: 12px;
  color: #666;
  line-height: 1.6;
}

:deep(.amap-lib-placeSearch .poibox:hover) {
  background-color: #f5f5f5;
}

/* 搜索建议样式 */
.search-suggestions {
  padding: 8px 0 4px;
}

:deep(.n-tag) {
  cursor: pointer;
  transition: all 0.3s ease;
}

:deep(.n-tag:hover) {
  background-color: #f0f0f0;
  transform: translateY(-1px);
}

:deep(.n-space) {
  flex-wrap: wrap;
  gap: 8px !important;
}
</style>